package com.example.statistics.ui.yw

import android.os.Bundle
import android.text.Editable
import android.view.View
import com.example.statistics.R
import com.example.statistics.bean.yw.*
import com.example.statistics.common.BaseActivity
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.net.callback.DataDialogHttpCallback
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityFinish
import com.example.statistics.utils.activityForResult
import com.google.gson.Gson
import com.jhj.httplibrary.HttpCall
import com.jhj.httplibrary.utils.ExtraRequestBodyUtils
import kotlinx.android.synthetic.main.activity_material_to_product.*
import kotlinx.android.synthetic.main.layout_processing.view.*
import kotlinx.android.synthetic.main.layout_purchase_type_title.view.*
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.toast
import java.math.BigDecimal
import java.util.Date

/**
 * 原料转换为成品
 */
class MaterialToProductActivity : BaseActivity() {

    private val processingMaterialList = mutableListOf<ProcessingMaterialBean>()
    private val processingProductList = mutableListOf<ProcessingProductBean>()
    private val processingBean = ProcessingBean()

    override val title: String
        get() = "原料加工"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_material_to_product)
        val id = intent.getIntExtra(Constants.ID, 0)
        tv_date.contentText = Date().format()

        topBarRightText("保存") {
            processingBean.date = tv_date.contentText
            processingBean.prefreight = tv_freight.textStringToNumber.toInt()
            processingBean.preProductionFee = tv_production_fee.textStringToNumber.toInt()
            processingBean.allPayment = processingBean.maleTotalPayment.addEx(processingBean.womanTotalPayment).toFloat()
            var materialTotalPrice = BigDecimal(0)
            var productTotalPrice = BigDecimal(0)
            processingMaterialList.forEach {
                materialTotalPrice = materialTotalPrice.addEx(it.totalPrice)
                it.date = tv_date.contentText.orEmpty()
            }
            processingProductList.forEach {
                productTotalPrice = productTotalPrice.addEx(it.preTotalPrice)
                it.date = tv_date.contentText.orEmpty()
            }
            processingBean.materialList = processingMaterialList
            processingBean.productList = processingProductList
            val json = Gson().toJson(processingBean)
            val requestBody = ExtraRequestBodyUtils.upJson(json)
            val url = if (id != 0) UrlConfig.PROCESSING_UPDATE else UrlConfig.PROCESSING_ADD
            HttpCall.post(url)
                .upRequestBody(requestBody)
                .enqueue(object : DataDialogHttpCallback<ProcessingBean>(this) {
                    override fun onSuccess(data: ProcessingBean?, resultType: ResultType) {
                        toast(data?.date.orEmpty())
                        activityFinish()
                    }
                })
        }

        initView()

        //原料
        material()
        layout_material_title.tv_title.contentText = "原料"
        layout_material_title.iv_add.onClick {
            val lastProcessingMaterial = processingMaterialList.last()
            if (lastProcessingMaterial.materialId == 0 ||
                lastProcessingMaterial.materialWeight == 0f ||
                lastProcessingMaterial.materialNumber == 0f
            ) {
                toast("补全原料信息后方可添加新原料")
                return@onClick
            }
            material()
        }
        //成品
        product()
        layout_product_title.tv_title.contentText = "成品"
        layout_product_title.iv_add.onClick {
            val lastProcessingProduct = processingProductList.last()
            if (lastProcessingProduct.productId == 0 ||
                lastProcessingProduct.productNumber == 0f ||
                lastProcessingProduct.productWeight == 0f
            ) {
                toast("补全成品信息后方可添加新成品")
                return@onClick
            }
            product()
        }
    }

    private fun initView() {
        tv_freight.afterTextChangedListener { _, _ ->
            profit()
        }
        //工费
        layout_payment_title.tv_title.contentText = "工费"
        layout_payment_title.iv_add.visibility = View.INVISIBLE
        processingBean.malePayment = 222f
        tv_male_payment.contentText = "222"
        tv_male.afterTextChangedListener { editable, _ ->
            processingBean.maleWorker = getEditableNumber(editable)
            processingBean.maleTotalPayment = processingBean.maleWorker.mulEx(processingBean.malePayment).toFloat()
            tv_male_total_payment.contentText = processingBean.maleTotalPayment.toString()
        }
        tv_male_payment.afterTextChangedListener { editable, _ ->
            processingBean.malePayment = getEditableNumber(editable)
            processingBean.maleTotalPayment = processingBean.maleWorker.mulEx(processingBean.malePayment).toFloat()
            tv_male_total_payment.contentText = processingBean.maleTotalPayment.toString()
        }
        tv_male_total_payment.afterTextChangedListener { _, _ ->
            profit()
        }


        processingBean.womanPayment = 165f
        tv_woman_payment.contentText = "165"
        tv_woman.afterTextChangedListener { editable, _ ->
            processingBean.womanWorker = getEditableNumber(editable)
            processingBean.womanTotalPayment = processingBean.womanWorker.mulEx(processingBean.womanPayment).toFloat()
            tv_woman_total_payment.contentText = processingBean.womanTotalPayment.toString()
        }
        tv_male_payment.afterTextChangedListener { editable, _ ->
            processingBean.womanPayment = getEditableNumber(editable)
            processingBean.womanTotalPayment = processingBean.womanWorker.mulEx(processingBean.womanPayment).toFloat()
            tv_woman_total_payment.contentText = processingBean.womanTotalPayment.toString()
            profit()
        }
        tv_woman_total_payment.afterTextChangedListener { _, _ ->
            profit()
        }

    }

    private fun material() {
        val view = inflater.inflate(R.layout.layout_processing, layout_material, false)
        val processingMaterialBean = ProcessingMaterialBean()
        var materialBean: MaterialBean? = null
        view.tv_product.onContentClicked { _ ->
            activityForResult<MaterialListActivity>(Constants.ACTION to Constants.SELECTOR) { intent ->
                materialBean = (intent?.getSerializableExtra(Constants.DATA) as MaterialBean?)
                materialBean?.let {
                    processingMaterialBean.materialId = it.ID
                    processingMaterialBean.materialName = it.materialName
                    processingMaterialBean.materialPrice = it.unitPrice
                    view.tv_product.contentText = it.materialName
                    view.et_price.contentText = it.unitPrice.toString()
                }
            }
        }

        view.et_number.afterTextChangedListener { editable, _ ->
            if (materialBean == null) {
                toast("请选择原料")
                editable?.replace(0, editable.length, "".trim { it <= ' ' })
                return@afterTextChangedListener
            }
            editable.maxLimit(this, materialBean!!.inventoryNumber)
            val number = getEditableNumber(editable)
            processingMaterialBean.materialNumber = number
            processingBean.materialNumber = processingMaterialList.sumEx { it.materialNumber }.toFloat()
            view.et_weight.contentText = number.mulEx(materialBean!!.specification).toString()
        }
        view.et_weight.afterTextChangedListener { editable, _ ->
            if (materialBean == null) {
                toast("请选择原料")
                editable?.replace(0, editable.length, "".trim { it <= ' ' })
                return@afterTextChangedListener
            }
            editable.maxLimit(this, materialBean!!.inventoryWeight)
            val weight = getEditableNumber(editable)
            val totalPrice = weight.mulEx(materialBean!!.unitPrice)
            processingMaterialBean.materialWeight = weight
            processingMaterialBean.totalPrice = totalPrice.toFloat()
            view.et_total_price.contentText = totalPrice.toString()

            val materialTotalWeight = processingMaterialList.sumEx { it.materialWeight }
            processingBean.materialWeight = materialTotalWeight.toFloat()
            layout_material_title.tv_fee.contentText = "（${materialTotalWeight}KG）"


            val productTotalWeight = processingProductList.sumEx { it.productWeight }
            if (materialTotalWeight.toFloat() != 0f && productTotalWeight.toFloat() != 0f) {
                processingBean.rise = productTotalWeight.mulEx(100).divEx(materialTotalWeight).toFloat()
                tv_rise.contentText = "${processingBean.rise}%"
            } else {
                processingBean.rise = 0f
                tv_rise.contentText = ""
            }
            profit()
        }
        layout_material.addView(view)
        processingMaterialList.add(processingMaterialBean)
    }


    private fun product() {
        val view = inflater.inflate(R.layout.layout_processing, layout_material, false)
        val processingProductBean = ProcessingProductBean()
        var productBean: ProductTypeBean? = null
        view.tv_product.onContentClicked { _ ->
            activityForResult<ProductTypeListActivity>(Constants.ACTION to Constants.SELECTOR) { intent ->
                productBean = (intent?.getSerializableExtra(Constants.DATA) as ProductTypeBean?)
                productBean?.let {
                    processingProductBean.productId = it.ID
                    processingProductBean.productName = it.productName
                    view.tv_product.contentText = it.productName
                }
            }
        }
        view.et_number.afterTextChangedListener { editable, _ ->
            if (productBean == null) {
                toast("请选择成品")
                editable?.replace(0, editable.length, "".trim { it <= ' ' })
                return@afterTextChangedListener
            }
            val number = getEditableNumber(editable)
            processingProductBean.productNumber = number
            processingBean.productNumber = processingProductList.sumEx { it.productNumber }.toFloat()
            view.et_weight.contentText = number.mulEx(productBean!!.specification).toString()
        }
        view.et_weight.afterTextChangedListener { editable, _ ->
            if (productBean == null) {
                toast("请选择成品")
                editable?.replace(0, editable.length, "".trim { it <= ' ' })
                return@afterTextChangedListener
            }

            val weight = getEditableNumber(editable)
            val totalPrice = weight.mulEx(processingProductBean.prePrice)
            processingProductBean.productWeight = weight
            processingProductBean.preTotalPrice = totalPrice.toFloat()
            view.et_total_price.contentText = totalPrice.toString()

            val productTotalWeight = processingProductList.sumEx { it.productWeight }
            processingBean.productWeight = productTotalWeight.toFloat()
            layout_product_title.tv_fee.contentText = "（${productTotalWeight}KG）"

            val materialTotalWeight = processingMaterialList.sumEx { it.materialWeight }
            if (materialTotalWeight.toFloat() != 0f && productTotalWeight.toFloat() != 0f) {
                processingBean.rise = productTotalWeight.mulEx(100).divEx(materialTotalWeight).toFloat()
                tv_rise.contentText = "${processingBean.rise}%"
            } else {
                processingBean.rise = 0f
                tv_rise.contentText = ""
            }
            profit()
        }

        view.et_price.labelText = "定价："
        view.et_price.afterTextChangedListener { editable, _ ->
            if (productBean == null) {
                toast("请选择成品")
                editable?.replace(0, editable.length, "".trim { it <= ' ' })
                return@afterTextChangedListener
            }
            processingProductBean.prePrice = getEditableNumber(editable)
            processingProductBean.preTotalPrice = processingProductBean.prePrice
                .mulEx(processingProductBean.productWeight).toFloat()
            view.et_total_price.contentText = processingProductBean.preTotalPrice.toString()
            profit()
        }
        layout_product.addView(view)
        processingProductList.add(processingProductBean)
    }


    private fun getEditableNumber(editable: Editable?): Float {
        return if (editable?.toString().isNumber()) {
            editable.toString().toFloat()
        } else {
            0f
        }
    }

    private fun profit(): Float {
        processingBean.preMaterialFee = processingMaterialList.sumEx { it.totalPrice }.toFloat()
        processingBean.preProductFee = processingProductList.sumEx { it.preTotalPrice }.toFloat()
        val profit = processingBean.preProductFee
            .subEx(processingBean.preMaterialFee)
            .subEx(tv_male_total_payment.textStringToNumber)
            .subEx(tv_production_fee.textStringToNumber)
            .subEx(tv_woman_total_payment.textStringToNumber)
            .subEx(tv_freight.textStringToNumber)
        processingBean.preProfit = profit.toInt()
        tv_profit.contentText = profit.toString()
        return profit.toFloat()
    }

}